package com.example.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
 * @author shenxiang
 * @date 2020/11/10 21:20
 * @description
 */
@Configuration
public class RedisConfig {

    @Value("${spring.redis.cluster.nodes}")
    private String redisNodes;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private Integer maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private Integer minIdle;

    @Value(("${spring.redis.jedis.pool.max-active}"))
    private Integer maxTotal;

    @Value("${spring.redis.timeout}")
    private Integer timeout;


    @Bean("jedisCluster")
    public JedisCluster getJedisCluster(){
        Set<HostAndPort> hostAndPorts = new HashSet<>();
        final String[] split = this.redisNodes.split(",");
        for (String s : split) {
            final String[] hostAndPort = s.split(":");
            hostAndPorts.add(new HostAndPort(hostAndPort[0],Integer.parseInt(hostAndPort[1])));
        }
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxTotal(maxTotal);
        return new JedisCluster(hostAndPorts,timeout,config);
    }
}
